package com.example.trb.controller.department;

import com.example.trb.dto.ObjectDTO;
import com.example.trb.entity.Department;
import com.example.trb.entity.ReviewForm;
import com.example.trb.service.department.DepartmentService;
import com.example.trb.service.review.ReviewFormService;
import com.example.trb.util.result.CommonResult;
import com.example.trb.util.result.ReturnCode;
import com.example.trb.util.result.UserReturnCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RestController
public class DepartmentController {
    @Autowired
    DepartmentService departmentService;
    @Autowired
    ReviewFormService reviewFormService;
    @Value("${session_user}")
    String userKey;

    @PutMapping("/department/reviewform")
    public CommonResult updateFormStatus(@RequestBody ReviewForm data) {
        reviewFormService.updateStatusById(data.getId(), data.getStatus());
        return CommonResult.success(null);
    }

    @GetMapping("/department/reviewform")
    public CommonResult getReviewForm(
            @RequestParam(value = "reviewYear", required = false) String reviewYear,
            @RequestParam(value = "status", required = false) String status,
            @RequestParam(value = "level", required = false) String level,
            HttpSession session
    ) {
        Department department = (Department) session.getAttribute(userKey);
        ObjectDTO dto = departmentService.listForm(department.getId(), status, reviewYear, level);
        return CommonResult.success(dto.getData());
    }

    @PostMapping("/department/login")
    public CommonResult login(
            @RequestBody @Validated Department data,
            HttpSession session
    ) {
        ObjectDTO dto = departmentService.login(data);
        ReturnCode returnCode = dto.getCode();

        if (returnCode == UserReturnCode.USER_NOT_EXIST) {
            return CommonResult.fail(returnCode.code(), returnCode.message());
        }
        if (returnCode == UserReturnCode.PASSWORD_OR_ACCOUNT_ERROR) {
            return CommonResult.fail(returnCode.code(), returnCode.message());
        }

        session.setAttribute(userKey, dto.getData());
        return CommonResult.success(dto.getData());
    }
}
